<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>OCTIS - Manage Experiments</title>

    <link href="{{ url_for('static', filename='styles/bootstrap.css') }}" rel="stylesheet">
    <link href="{{ url_for('static', filename='styles/styles.css') }}" rel="stylesheet">

    <link rel="icon" href="{{ url_for('static', filename='images/favicon.png') }}">
    <style>
        ul li {
            font-size: 18px;
            margin: 10px 0;

        }

        div.choice {
            border-radius: 25px;
            border: 2px solid #3254d0;
            padding: 20px;
            background-color: #a5b5f1;
        }

        .send-button {
            margin: 2px;
        }

    </style>
</head>

<body>
<div>
    <ul class="navbar">
        <li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('home') }}"><img style="width:20%"
                                                                    src="{{ url_for('static', filename='images/logo.png') }}"
                                                                    alt="alternative"></a>
        </li>
        <li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('home') }}">HOME</a>
        </li>
        <li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('CreateExperiments') }}">CREATE EXPERIMENTS</a>
        </li>
        <li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('VisualizeExperiments') }}">VISUALIZE
                EXPERIMENTS</a>
        </li>
        <li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('ManageExperiments') }}">MANAGE EXPERIMENTS</a>
        </li>
        <!--<li class="navbarEl">
            <a class="navbarLink" href="{{ url_for('serverClosed') }}">CLOSE DASHBOARD</a>
        </li>
        -->
    </ul>
</div>

<header id="header">
    <div>
        <h1 style="text-align: center">Manage the experiment queue
            <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample"
                    aria-expanded="false" aria-controls="collapseExample">
                Click here to read the instructions!
            </button>
        </h1>
    </div>
</header>
<div class="outContainer">
    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div class="text-container">
                    <div class="collapse" id="collapseExample">
                        <div class="card card-body">
                            <p class="lead"> In this page, you can manage the queue of the experiments that
                                you have defined in the
                                <a class="btn btn-primary" href="{{ url_for('CreateExperiments') }}"
                                   role="button">Create Experiments</a>
                                page. The experiment in the top is the currently running experiment.
                                You can
                            <ul>
                                <li> Stop a running experiment by clicking on
                                    <button type="button"
                                            class="btn btn-warning">Stop Experiment
                                    </button>
                                </li>
                                <li> Start or restart an experiment by clicking on
                                    <button type="button"
                                            class="btn btn-success">Start Experiment
                                    </button>
                                </li>
                                <li> Delete an experiment by clicking on
                                    <button type="button"
                                            class="btn btn-danger">Delete Experiment
                                    </button>
                                    .
                                    The experiment will be removed from the queue but you can still see the results
                                    in the
                                    <a class="btn btn-primary" href="{{ url_for('VisualizeExperiments') }}"
                                       role="button">Visualize Experiments</a>
                                    page.
                                </li>
                                <li> Drag and drop an experiment to sort the experiments queue. You can do this
                                    operation only if the
                                    involved experiments are not running.
                                </li>
                            </ul>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<hr>
<div class="outContainer">
    <ul id="container" class="container" style="list-style: none;"></ul>
    <div class="container">
        <div class="row">
            <a class="btn btn-dark" href="{{ url_for('serverClosed') }}" role="button">Safely Close the Dashboard </a>
        </div>
    </div>
</div>

<div class="footer">
    <div class="container">
        <h4 style="color:white;">OCTIS</h4>
        <p class="white" style="color:white;">Optimizing and Comparing Topic Models is Simple!</p>
    </div>
</div>

<script type="text/javascript" src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='popper.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='bootstrap.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='jquery.easing.min.js') }}"></script>
<script>

        function getParams(vars) {
            return vars;
        }

        function stopCurrent() {
            $.ajax(
                {
                    type: 'POST',
                    url: "/pauseExp",
                    success: function (data) { console.log("stopped") }
                });
            el = $(".running:eq(0)")
            el.attr("draggable", true)
            el.children().css("background-color", "#a5b5f1")
            buttonsDiv = document.getElementById("container").firstChild.firstChild.getElementsByTagName('div')[1];

            startExp = document.createElement("button")
            startExp.classList.add("btn")
            startExp.classList.add("btn-success")
            startExp.id = "startButton"
            startExp.addEventListener("click", start)
            startExp.innerHTML = "Start running"

            buttonsDiv.append(startExp)
            $("#stopButton").remove()

            el.removeClass("running")


        }

        function start() {
            $.ajax(
                {
                    type: 'POST',
                    url: "/startExp",
                    success: function (data) { console.log("stopped") }
                });
            el = $("#container li").first()
            el.attr("draggable", false)
            el.children().css("background-color", "#de8787")

            buttonsDiv = document.getElementById("container").firstChild.firstChild.getElementsByTagName('div')[1];

            stopExp = document.createElement("button")
            stopExp.classList.add("btn")
            stopExp.classList.add("btn-warning")
            stopExp.id = "stopButton"
            stopExp.addEventListener("click", stopCurrent)
            stopExp.innerHTML = "Stop Experiment"

            buttonsDiv.append(stopExp)
            $("#startButton").remove()

            el.addClass("running")


        }

        order = getParams({{ order| tojson}});
        exps = getParams({{ experiments| tojson}});
        running = getParams({{ running| tojson}});

        element = document.getElementById("container")



        if (running != null) {
            child = document.createElement("li")
            child.classList.add("sortable-bulk")
            child.setAttribute('draggable', false);
            child.dataset.expName = running
            child.classList.add("running")
            child.id = 0;


            buttonsDiv = document.createElement("div")
            buttonsDiv.classList.add("col-4")
            deleteButton = document.createElement("button")
            deleteButton.classList.add("btn")
            deleteButton.classList.add("btn-danger")
            deleteButton.innerHTML = "Delete experiment";
            deleteButton.dataset.expId = running
            deleteButton.dataset.childname = child.id
            deleteButton.addEventListener("click", deleteFromOrder)

            stopButton = document.createElement("button")
            stopButton.id = "stopButton"
            stopButton.classList.add("btn")
            stopButton.classList.add("btn-warning")
            stopButton.innerHTML = "Stop Experiment"
            stopButton.addEventListener("click", stopCurrent)

            div = document.createElement("div")
            div.style.backgroundColor = "#de8787"
            div.classList.add("choice")
            div.classList.add("row")

            current_iteration = 0;
            total_iterations = 100;
            if (("current_iteration" in exps[running])) {
                current_iteration = exps[running]["current_iteration"]
                total_iterations = exps[running]["total_iterations"]
            }
            percentage = ((current_iteration / total_iterations) * 100).toFixed(0).toString()
            div.innerHTML = "<div class='col-8'><b> Name of the experiment: " + exps[running]["experimentId"] +
                " (Name of the batch: " + exps[running]["batchId"] + " )</b><br>" +
                "<b>Model:</b> " + exps[running]["model"]["name"] +
                "<br><b>Search space:</b> " + JSON.stringify(exps[running]["optimization"]["search_spaces"]) +
                "<br><b>Dataset:</b> " + exps[running]["dataset"] +
                "<br><b>Metric to optimize:</b> " + exps[running]["optimize_metrics"][0]["name"] +
                "<br><b>Progress: </b> <span class=\"progress\"><span class=\"progress-bar\" role=\"progressbar\" style=\"width: " +
                percentage + "%;\" aria-valuenow=\"" + percentage+ "\" aria-valuemin=\"0\" aria-valuemax=\"100\">" +
                + percentage + "%</span></span><br>"

            buttonsDiv.appendChild(deleteButton)
            buttonsDiv.appendChild(stopButton)
            div.appendChild(buttonsDiv)


            child.appendChild(div)
            element.appendChild(child)
        }



        for (i = 0; i < order.length; i++) {

            child = document.createElement("li")
            child.classList.add("sortable-bulk")
            child.setAttribute('draggable', true);
            child.dataset.expName = order[i]
            child.id = (i + 1).toString()


            buttonsDiv = document.createElement("div")
            buttonsDiv.classList.add("col-4")
            deleteButton = document.createElement("button")
            deleteButton.classList.add("btn")
            deleteButton.classList.add("btn-danger")
            deleteButton.innerHTML = "Delete experiment";
            deleteButton.dataset.expId = order[i]
            deleteButton.dataset.childname = child.id
            deleteButton.addEventListener("click", deleteFromOrder)


            div = document.createElement("div")
            div.classList.add("choice")
            div.classList.add("row")

            current_iteration = 0;
            total_iterations = 100;
            if (("current_iteration" in exps[order[i]])) {
                current_iteration = exps[order[i]]["current_iteration"]
                total_iterations = exps[order[i]]["total_iterations"]
            }
            percentage = ((current_iteration / total_iterations) * 100).toFixed(0).toString()

            div.innerHTML = "<div class='col-8'><b> Name of the experiment: " + exps[order[i]]["experimentId"] +
                " (Name of the batch: " + exps[order[i]]["batchId"] + " )</b><br>" +
                "<b>Model:</b> " + exps[order[i]]["model"]["name"] +
                "<br><b>Search space:</b> " + JSON.stringify(exps[order[i]]["optimization"]["search_spaces"]) +
                "<br><b>Dataset:</b> " + exps[order[i]]["dataset"] +
                "<br><b>Metric to optimize:</b> " + exps[order[i]]["optimize_metrics"][0]["name"] +
                "<br><b>Progress: </b> <span class=\"progress\"><span class=\"progress-bar\" role=\"progressbar\" style=\"width: " +
                percentage + "%;\" aria-valuenow=\"" + percentage+ "\" aria-valuemin=\"0\" aria-valuemax=\"100\">" +
                + percentage + "%</span></span><br>"


            buttonsDiv.appendChild(deleteButton)

            if (i == 0 && running == null) {
                startButton = document.createElement("button")
                startButton.id = "startButton"
                startButton.classList.add("btn")
                startButton.classList.add("btn-success")
                startButton.innerHTML = "Start Experiment"
                startButton.addEventListener("click", start)
                buttonsDiv.appendChild(startButton)
            }

            div.appendChild(buttonsDiv)


            child.appendChild(div)
            element.appendChild(child)

        }




        var dragging = null;

        document.addEventListener('dragstart', function (event) {
            pr = event.target;
            while (pr.tagName != "li" && pr.tagName != "LI") {
                pr = pr.parentNode
            }
            dragging = pr
            event.dataTransfer.setData('text/html', dragging);
        });

        document.addEventListener('dragover', function (event) {
            event.preventDefault();
        });

        document.addEventListener('drop', function (event) {
            event.preventDefault();
            pr = event.target.parentNode
            while (pr.tagName != "li" && pr.tagName != "LI") {
                pr = pr.parentNode
            }
            if (!pr.classList.contains("running")) {
                prbButtonsDiv = $(pr.firstChild.getElementsByTagName('div')[1])
                draggingButtonsDiv = $(dragging.firstChild.getElementsByTagName('div')[1])
                tmp = null;
                if (prbButtonsDiv.children().length > 1) {
                    prbButtonsDiv.children().eq(1).unbind("click")
                    tmp = prbButtonsDiv.children().eq(1).clone()
                } else if (draggingButtonsDiv.children().length > 1) {
                    draggingButtonsDiv.children().eq(1).unbind("click")
                    tmp = draggingButtonsDiv.children().eq(1).clone()
                }

                pr.parentNode.insertBefore(dragging, pr);
                if (tmp != null) {
                    $("#" + tmp.attr('id')).remove();
                    buttonsDiv = document.getElementById("container").firstChild.firstChild.getElementsByTagName('div')[1];
                    buttonsDiv = $(buttonsDiv)
                    if (tmp.attr('id') == "startButton") {
                        tmp.on("click", start)
                    } else {
                        tmp.on("click", stopCurrent)
                    }

                    buttonsDiv.append(tmp)
                }

            }
            update()
        });


        function deleteFromOrder(evt) {
            id = evt.currentTarget.dataset.expId
            childname = evt.currentTarget.dataset.childname
            child = document.getElementById(childname)
            $.ajax(
                {
                    type: 'POST',
                    url: "/deleteExp",
                    contentType: 'application/json;charset=UTF-8',
                    dataType: 'json',
                    data: JSON.stringify({ "data": id }),
                    success: function (data) {
                        console.log("deleted " + id)
                        child.remove()
                        if ($("#startButton").length == 0 && $("#stopButton").length == 0) {
                            buttonsDiv = document.getElementById("container").firstChild.firstChild.getElementsByTagName('div')[1];
                            startExp = document.createElement("button")
                            startExp.classList.add("btn")
                            startExp.classList.add("btn-success")
                            startExp.id = "startButton"
                            startExp.addEventListener("click", start)
                            startExp.innerHTML = "Start Experiment"

                            buttonsDiv.append(startExp)
                        }
                    }
                })
        }


        function update() {
            element = document.getElementById("container")

            newOrder = []

            var i = 0;
            if (document.getElementsByClassName("running").length > 0) {
                i = 1;
            }

            for (i; i < element.children.length; i++) {
                newOrder.push(element.children[i].dataset.expName)
            }

            $.ajax(
                {
                    type: 'POST',
                    url: "/updateOrder",
                    contentType: 'application/json;charset=UTF-8',
                    dataType: 'json',
                    data: JSON.stringify({ "data": newOrder }),
                    success: function (data) {
                        console.log(newOrder)
                    }
                })
        }

</script>

</body>

</html>
